package com.ls.x.tool;

import java.util.Calendar;
import java.util.Date;

import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.util.Log;
import android.view.View;
import android.widget.DatePicker;
import android.widget.DatePicker.OnDateChangedListener;
import android.widget.TimePicker;
import android.widget.TimePicker.OnTimeChangedListener;
import com.ls.x.R;

public class DateTimeTool {

	private int year;
	private int month;
	private int day;
	private int hour;
	private int minute;
	private Date currentDateTime;

	// 通过传入的Builder和View对象，提供一个设置菜单的Spinner
	public Date getDateTimeSpinner(Builder builder, View view, Date current) {

		this.currentDateTime = current;

		builder.setTitle("设置开始时间");

		// 上面一段分解开来即如下代码
		// LayoutInflater inflater = getLayoutInflater();
		// View view = inflater.inflate(R.layout.delaynote, null);
		// TableLayout delayNote = (TableLayout)view;

		builder.setView(view);

		// 获得出线在对话框中的DatePicker和TimePicker
		DatePicker datePicker = (DatePicker) view.findViewById(R.id.datePicker);
		TimePicker timePicker = (TimePicker) view.findViewById(R.id.timePicker);
		if (currentDateTime == null) {
			Calendar c = Calendar.getInstance();
			year = c.get(Calendar.YEAR);
			month = c.get(Calendar.MONTH);
			day = c.get(Calendar.DAY_OF_MONTH);
			hour = c.get(Calendar.HOUR_OF_DAY);
			minute = c.get(Calendar.MINUTE);
		}

		datePicker.init(year, month, day, new OnDateChangedListener() {

			@Override
			public void onDateChanged(DatePicker view, int newyear,
					int newmonth, int newday) {
				year = newyear;
				month = newmonth;
				day = newday;
			}
		});
		timePicker.setCurrentHour(hour);
		timePicker.setCurrentMinute(minute);
		timePicker.setOnTimeChangedListener(new OnTimeChangedListener() {
			@Override
			public void onTimeChanged(TimePicker view, int newhour,
					int newminute) {
				hour = newhour;
				minute = newminute;
			}
		});

		// 为对话框设置”确定“按钮
		// 注意，为了跟View中的button的事件却分，需要在OnClickListener前面加上DialogInterface
		builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				Log.d("lijing", "点击了确定按钮");
				currentDateTime = new Date(year - 1900, month, day, hour,
						minute);
			}
		});
		// 为对话框设置”确定“按钮
		builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				Log.d("lijing", "点击了取消按钮");
			}
		});

		builder.create().show();

		System.out.println("lijing" + currentDateTime);

		return currentDateTime;
	}
}
